import { Injectable } from '@nestjs/common';
import { CreateCollectDto } from './dto/create-collect.dto';
import { Collect } from './entities/collect.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { BusinessException } from '../../common/exceptions/business.exception';
import { ErrorCode } from '../../common/errorcode';
import { Article } from '../article/entities/article.entity';
import { User } from '../user/entities/user.entity';
@Injectable()
export class CollectService {
  constructor(
    @InjectRepository(Collect) private collectRepository: Repository<Collect>,
    @InjectRepository(Article) private articleRepository: Repository<Article>,
    @InjectRepository(User) private userRepository: Repository<User>
  ) { }
  async findAllbyarticleid(articleid: string) {
    return await this.collectRepository.find({
      where: {
        articleid,
      },
    });
  }
  async findAllbyuserid(userid) {
    return await this.collectRepository.find({
      where: {
        userid: userid.userid,
      },
    });
  }
  async update(createCollectDto) {
    if (createCollectDto.iscollect) {

      const iscollected = await this.collectRepository.findOne({
        where: {
          userid: createCollectDto.userid,
          articleid: createCollectDto.articleid,
        },
      });
      if (iscollected) throw new BusinessException('您已收藏该文章', ErrorCode.FORBIDDEN);
      await this.collectRepository.save(createCollectDto);

    } else {
      const iscollected = await this.collectRepository.delete({
        userid: createCollectDto.userid,
        articleid: createCollectDto.articleid,
      });
      if (!iscollected) throw new BusinessException('您未收藏该文章', ErrorCode.FORBIDDEN);
    }

    return true;
  }

  async remove(id) {
    return await this.collectRepository.delete(id);
  }

  async findAllArticlesByUserId(userid: string) {
    // 先查询用户收藏的所有文章ID
    const collects = await this.collectRepository.find({
      where: {
        userid: userid,
      },
    });

    // 提取文章ID列表
    const articleIds = collects.map(collect => collect.articleid);

    if (articleIds.length === 0) {
      return [];
    }
    const articles: any = []
    for (let index = 0; index < articleIds.length; index++) {
      const element: any = await this.articleRepository.findOne({
        where: {
          articleid: articleIds[index] as any,
        },
        relations: ['user'], // 关联查询作者信息
      });
      
      articles.push(element)

    }

    // 将收藏时间和文章信息合并
    const result = articles.map(article => {
      const collect = collects.find(c => c.articleid === article.articleid);
      return {
        ...article,
        collect_time: collect?.create_time, // 收藏时间
      };
    });

    return result;
  }
}
